#!/usr/bin/env python
# this file is for adapt qingcloud python api
#
# Auth: Guosheng Cui 
#
# this file is for qing cloud configuration, all qing cloud ref cfg can
# be found in this file.

import yaml
from qing_log import  Log
import os

log = Log.get_log()



class QingConfig():
    '''
    this is the class for qingcloud configuration
    '''
    cfg_file='/home/ubuntu/test/engine/resources/qingresources/qingconfig.yaml'
    
    handle = None
    content = None
    
    @staticmethod
    def _init():
        file = QingConfig.cfg_file
   
        QingConfig.handle = open(file)
        QingConfig.content = yaml.load(QingConfig.handle)

    def __init__(self, cfg = ''):
        if cfg != '':
            QingConfig.cfg_file = cfg
        QingConfig._init()
    
    @staticmethod
    def get_image_id(image):
        i = 'neucloud-ubuntu-12.04-cfntools'
        if QingConfig.content == None:
            QingConfig._init()
            
        imgs = QingConfig.content['image']
        
        for img in imgs:
            if img.has_key(i):
                return img[i]

        log.error('can not find image id')
        return ''
        
    @staticmethod
    def get_flavor(flavor):
        if QingConfig.content == None:
            QingConfig._init()
        print(QingConfig.content)
        
        fl = QingConfig.content['flavor']
                 
        for f in fl:
            if f == flavor:
                return flavor

        log.error('can not find the flavor id')
        return ''
    
    @staticmethod
    def get_metaserver():
        if QingConfig.content == None:
            QingConfig._init()
            
        f1 = QingConfig.content['meatserver']
        
        print(f1)
        return f1[0]      

    @staticmethod
    def get_networdid(network):
        if QingConfig.content == None:
            QingConfig._init()
    
        return ['vxnet-e5tvljq']
        
    @staticmethod
    def write_userdata(instance, userdata):
        path = QingConfig.get_metaserver()+instance
        if os.path.exists(path):
            os.remove(path)
        
        os.mkdir(path)
        f = open(path+'/user-data-file', 'w')
        f.write(userdata)
        f.close

    @staticmethod
    def remove_userdata(instance):
        path = QingConfig.get_metaserver()+instance
        if os.path.exists(path):
            #os.removedirs(path) 
            __import__('shutil').rmtree(path)

        
if __name__ == "__main__":
    '''
    TEST FOR THIS CLASS
    '''
    
    print(QingConfig.get_flavor('c1m1'))
    print(QingConfig.get_image_id('ubu1204cloudinit'))
